package com.atguigu.app.dwd.db;
//动态分流不需要加工的事实表

//todo 1.获取执行环境
//todo 2.读取kafka topic_db主题数据创建流
//todo 3.过滤数据并将数据转换为json对象 主流
//todo 4.使用flink CDC读取配置信息表
//todo 5.将配置信息流转换为广播流
//todo 6.连接两个流
//todo 7.根据配置信息过滤主流数据
//todo 8.将数据动态写出到kafka不同主题
//todo 9.启动任务

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TableProcess;
import com.atguigu.func.DwdTableProcessFunction;
import com.atguigu.utils.KafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.util.Collector;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;

//BaseDBApp动态分流不需要加工的事实表
//数据流：web/app -> mysql(binlog) -> maxwell -> kafka(ods) -> flinkApp(也用到了flinkCDC) -> kafka(dwd)
//程序 ：   Mock -> mysql         -> maxwell -> kafka(zk)  ->BaseDBApp                   -> kafka(zk)
public class BaseDBApp {
    public static void main(String[] args) throws Exception {
        //todo 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //todo 生产环境一定要写，测试注释掉，否则每次测试都得开hdfs
//        需要从checkpoint或savepoint启动程序
//        //2.1 开启checkpoint，每隔5s钟做一次ck，并指定ck的一致性语义
//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);//exactly once：默认barrier对齐
//        //2.2 设置超时时间为1min
//        env.getCheckpointConfig().setCheckpointTimeout(60*1000L);//设置超时时间设置checkpoint的超时时间为1min，是指做一次checkpoint的时间；如果超时则认为本次checkpoint失败，这个checkpoint就丢了，继续一下一次checkpoint即可
//        //2.3设置两次重启的最小时间间隔为3s
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        //2.4设置任务关闭的时候保留最后一次ck数据
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        //2.5 指定从ck自动重启策略
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                3, Time.days(1L),Time.minutes(1L)
//        ));
//        //2.6 设置状态后端
//        env.setStateBackend(new HashMapStateBackend());//本地状态位置
//        env.getCheckpointConfig().setCheckpointStorage(
//                "hdfs://hadoop102:8020/flinkCDC/220828"
//        );//checkpoint状态位置
//        //2.7 设置访问HDFS的用户名
//        System.setProperty("HADOOP_USER_NAME","atguigu");

        //todo 2.读取kafka topic_db主题数据创建流
        DataStreamSource<String> kafkaDS = env.addSource(KafkaUtil.getFlinkKafkaConsumer("topic_db", "base_db_app_220828"));

        //todo 3.过滤数据并将数据转换为json对象 主流

        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                if (value != null) {
                    try {
                        JSONObject jsonObject = JSON.parseObject(value);
                        out.collect(jsonObject);
                    } catch (Exception ignored) {

                    }
                }
            }
        });
//        jsonObjDS.print();

        //todo 4.使用flink CDC读取配置信息表
        MySqlSource<String> sqlSource = MySqlSource.<String>builder()//如果想要返回JSONObject，需要自定义反序列化器
                .hostname("hadoop102")
                .port(3306)
                .username("root")
                .password("123456")
                .databaseList("gmall-220828-config")
                .tableList("gmall-220828-config.table_process")
                .startupOptions(StartupOptions.latest())//open方法
                .deserializer(new JsonDebeziumDeserializationSchema())//JsonDebeziumDeserializationSchema()返回的是String类型，如果想要返回JSONObject，需要自定义反序列化器
                .build();

        DataStreamSource<String> mysqlSource = env.fromSource(sqlSource, WatermarkStrategy.noWatermarks(), "MysqlSource");

        //todo 5.将配置信息流转换为广播流
        //此时key应该是表名+类型
        MapStateDescriptor<String, TableProcess> mapStateDescriptor = new MapStateDescriptor<>("map-state", String.class, TableProcess.class);
        BroadcastStream<String> broadcastDS = mysqlSource.broadcast(mapStateDescriptor);

        //todo 6.连接两个流
        BroadcastConnectedStream<JSONObject, String> connectedStream = jsonObjDS.connect(broadcastDS);

        //todo 7.根据配置信息过滤主流数据
        SingleOutputStreamOperator<JSONObject> processDS = connectedStream.process(new DwdTableProcessFunction(mapStateDescriptor));

        //todo 8.将数据动态写出到kafka不同主题（主题名就是主流返回的value里sink_table对应的value值）
        processDS.print("主流过滤后的数据");
//        processDS.addSink(KafkaUtil.getFlinkKafkaProducer());
        processDS.addSink(KafkaUtil.getFlinkKafkaProducer(new KafkaSerializationSchema<JSONObject>() {//------------!!!!-------------------
            @Override
            public ProducerRecord<byte[], byte[]> serialize(JSONObject value, @Nullable Long timestamp) {
                System.out.println("Topic:"+value.getString("sink_table"));
                return new ProducerRecord<byte[], byte[]>(value.getString("sink_table"),value.getString("data").getBytes());//将data写到sink_table对应的value值的主题里
            }
        }));


        //todo 9.启动任务
        env.execute("baseDBApp");


    }
}
